import { isArray } from 'lodash-es'

export { default as http } from './request'
export { default as storage } from './storage'

/**
 * 列表转树形
 */
export function deepTree(list: any[], sort?: 'desc' | 'asc'): any[] {
  const newList: any[] = []
  const map: any = {}

  list
    .map((e) => {
      map[e.id] = e
      return e
    })
    .forEach((e) => {
      const parent = map[e.parentId]

      if (parent) {
        ;(parent.children || (parent.children = [])).push(e)
      } else {
        newList.push(e)
      }
    })
  return newList
}

/**
 * 树形转列表
 */
export function revDeepTree(list: any[]) {
  const arr: any[] = []
  let id = 0

  function deep(list: any[], parentId: number) {
    list.forEach((e) => {
      if (!e.id) {
        e.id = ++id
      }

      if (!e.parentId) {
        e.parentId = parentId
      }

      arr.push(e)

      if (e.children && isArray(e.children) && e.id) {
        deep(e.children, e.id)
      }
    })
  }

  deep(list || [], 0)

  return arr
}
